package cn.xaut.数组;

public class demo3 {

    // 滑动窗口的优化1
    // 遇到字母不需要用 contains 方法
    // 应该直接用数组看是否存在
    public int lengthOfLongestSubstring2(String s) {

        int[] freq = new int[256];
        int len = s.length();
        char[] cs = s.toCharArray();
        int res = 0;
        int l = 0, r = 0;
        
        while (l < len) {
            if (r < len && freq[cs[r]] == 0) { // 不包含 cs[r] 的话
                freq[cs[r]] ++;
                r ++;
            } else {
                freq[cs[l]] --;
                l ++;
            }
            res = Math.max(res, r - l);
        }
        
        return res;
    }

        // 滑动窗口
    public int lengthOfLongestSubstring(String s) {

        if (s.equals("") || s == null)
            return 0;
        if (s.length() == 1)
            return 1;
        
        int l = 0, r = 1;
        String t = s.substring(l, r);
        int res = t.length();
        while (l < s.length()) {
            if (r < s.length() && !t.contains(s.charAt(r) + "")) {
                r ++;
                t = s.substring(l, r);
            } else {    // t.contains(cs[r] + "")
                l ++;
                t = t.substring(1);
            }
            res = Math.max(res, t.length());
        }
        
        return res;
    }

    public static void main(String[] args) {

//        "abc".substring(1);
        System.out.println(new demo3().lengthOfLongestSubstring2("abcabcbb"));//3
        System.out.println(new demo3().lengthOfLongestSubstring2("bbbbb"));//1
        System.out.println(new demo3().lengthOfLongestSubstring2("pwwkew"));//3
        System.out.println(new demo3().lengthOfLongestSubstring2(""));//0
    }
}
